package indi.jp.project.core.service.impl;

import indi.jp.project.core.dao.BaseDao;
import indi.jp.project.core.entity.JsonResult;
import indi.jp.project.core.entity.User;
import indi.jp.project.core.service.LoginService;
import indi.jp.project.core.util.JwtUtil;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Service
public class LoginServiceImpl implements LoginService {

    private BaseDao baseDao;

    public LoginServiceImpl(BaseDao baseDao) {
        this.baseDao = baseDao;
    }

    @Override
    public JsonResult validateUser(User entity) {
        JsonResult res;
        try {
            User user = (User) baseDao.findByObject("userMapper.loadUserByUsername", entity);
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            if(user == null){
                res = JsonResult.failure("账号或密码错误");
                return res;
            }
            if(!encoder.matches(entity.getPassword(), user.getPassword())){
                res = JsonResult.failure("账号或密码错误");
                return res;
            }
            if(user.getState() == 1){
                res = JsonResult.failure("用户已被锁定");
                return res;
            }
            if(user.getState() == 9){
                res = JsonResult.failure("用户已离职");
                return res;
            }
            List<String> list = new ArrayList<>();
            list.add("sys:menu:query");
            user.setAuthorities(list);
            String token = JwtUtil.createToken(user);
            res = JsonResult.success(token);
        } catch (SQLException e) {
            e.printStackTrace();
            res = JsonResult.error();
        }
        return res;
    }
}
